<?php

namespace Simanx\Spes\Commands;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Simanx\Spes\Module\Module;
use Simanx\Spes\Module\ModuleManager;

class MakeModuleCommand extends Command
{
    protected $signature = 'spes:make-module {name}';

    protected $description = '创建模块';

    public function handle()
    {
        $moduleName = $this->argument('name');
        /** @var ModuleManager $moduleManager */
        $moduleManager = app(ModuleManager::class);
        if ($moduleManager->hasModule($moduleName)) {
            $this->error("模块已经存在: $moduleName");
            return;
        }

        $module = new Module($moduleName);
        $localFs = new Filesystem();
        $moduleRootPath = $module->path();
        $localFs->ensureDirectoryExists($module->path());
        $generatorDirs = config('spes.module.generator.dirs', []);
        foreach ($generatorDirs as $dir) {
            $path = sprintf('%s%s%s', $moduleRootPath, DIRECTORY_SEPARATOR, $dir);
            if ($localFs->makeDirectory($path)) {
                $this->line('创建文件夹成功: ' . $path);
            } else {
                $this->warn('创建文件夹失败: ' . $path);
            }
        }

        $generatorFiles = config('spes.module.generator.files', []);
        foreach ($generatorFiles as $file) {
            $path = sprintf('%s%s%s', $moduleRootPath, DIRECTORY_SEPARATOR, $file);
            if ($localFs->put($path, '')) {
                $this->line('创建文件成功: ' . $path);
            } else {
                $this->warn('创建文件失败: ' . $path);
            }
        }

        $this->info('创建模块成功: ' . $moduleName);
    }
}